package top.biangege.bbs.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.biangege.bbs.entity.Result;
import top.biangege.bbs.entity.User;
import top.biangege.bbs.entity.bo.UserLoginBo;
import top.biangege.bbs.mapper.UserMapper;
import top.biangege.bbs.service.UserService;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    private UserMapper userMapper;

    @Override
    public Result login(UserLoginBo userLoginBo) {
        if (!StringUtils.isNotBlank(userLoginBo.getUserLoginUsername()) || !StringUtils.isNotBlank(userLoginBo.getUserLoginPassword())) {
            return Result.error("用户名密码不能为空");
        }

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", userLoginBo.getUserLoginUsername()));

        if (user == null) {
            return Result.error("用户名不存在");
        }

        if (!StringUtils.equals(user.getUserPassword(), userLoginBo.getUserLoginPassword())) {
            return Result.error("密码错误");
        }
        String token = JWT.create().withAudience(user.getUserId().toString())
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + (1000 * 60 * 24)))
                .sign(Algorithm.HMAC256(user.getUserId().toString()));

        return Result.success(token);
    }
}
